package demo.controller;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.ScopeType;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.security.Identity;

import demo.entity.UploadedFile;

@SuppressWarnings("unchecked")
public abstract class Controller implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Log log = LogFactory.getLog(Controller.class);

    /**
     * This is to create an alias called 'controller' for the current page
     */
    @Out(scope=ScopeType.CONVERSATION)
    private Controller controller;

    protected Controller() {
        this.controller = this;
    }

    public Controller getController() {
        return controller;
    }

    public void setController(Controller controller) {
        this.controller = controller;
    }

    static void reloginAs(String username, String password) {
        // Identity.instance().logout();
        Contexts.getSessionContext().set("org.jboss.seam.sessionInvalid", false);
        Identity.instance().setRememberMe(true);
        Identity.instance().setUsername(username);
        Identity.instance().setPassword(password);
        Identity.instance().login();

        log.info("Logged in: " + Identity.instance().getUsername());
    }

    protected Map<String, Object> describe() {
        // return BeanUtilsBean.getInstance().describe(this);
        Map<String, Object> retVal = new HashMap<String, Object>();
        retVal.putAll(new BeanMap(this));
        return retVal;
    }
    
    protected String toText(String arg) {
        return arg;
    }

    protected List<String> toTextList(List<String> arg) {
        return arg;
    }

    protected UploadedFile toFile(UploadedFile arg) {
        return arg;
    }

    protected String fromInt(Integer arg) {
        if (arg == null) {
            return null;
        }
        
        return String.valueOf(arg);
    }

    protected Integer toInt(String arg) {
        if (arg == null) {
            return null;
        }
        
        return Integer.parseInt(arg);
    }

    protected String fromBoolean(Boolean arg) {
        if (arg == null) {
            return null;
        }
        
        return String.valueOf(arg);
    }

    protected Boolean toBoolean(String arg) {
        if (arg == null) {
            return null;
        }
        
        return Boolean.parseBoolean(arg);
    }
}// clickframes::version=3253250427::clickframes